//
//  ContentView.swift
//  yubook
//
//  Created by ryven on 2025/3/27.
//

import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(filter: #Predicate<Folder> { folder in
        folder.parent == nil
    }) private var rootFolders: [Folder]
    @State private var selectedFolder: Folder?
    @State private var selectedNote: Note?
    @State private var searchText = ""
    @State private var showingNewFolderSheet = false
    @State private var showingRenameSheet = false
    @State private var newFolderName = ""
    @State private var folderToRename: Folder?
    
    var body: some View {
        NavigationSplitView {
            // 侧边栏 - 文件夹列表
            FolderListView(
                folders: rootFolders,
                selectedFolder: $selectedFolder,
                selectedNote: $selectedNote,
                onNewFolder: { showingNewFolderSheet = true },
                onRenameFolder: { folder in
                    folderToRename = folder
                    newFolderName = folder.name
                    showingRenameSheet = true
                }
            )
        } content: {
            // 中间栏 - 笔记列表
            NoteListView(selectedFolder: selectedFolder, selectedNote: $selectedNote)
        } detail: {
            // 右侧栏 - 笔记编辑区
            if let note = selectedNote {
                NoteEditorView(note: note)
            } else {
                Text("选择或创建一个笔记")
                    .foregroundColor(.secondary)
            }
        }
        .searchable(text: $searchText, prompt: "搜索笔记")
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button(action: createNewNote) {
                    Label("新建笔记", systemImage: "square.and.pencil")
                }
            }
        }
        .sheet(isPresented: $showingNewFolderSheet) {
            NewFolderSheet(isPresented: $showingNewFolderSheet, folderName: $newFolderName, onSave: createNewFolder)
        }
        .sheet(isPresented: $showingRenameSheet) {
            RenameFolderSheet(
                isPresented: $showingRenameSheet,
                folderName: $newFolderName,
                onSave: renameFolder
            )
        }
        .onAppear {
            ensureDefaultFolderExists()
        }
    }

    private func ensureDefaultFolderExists() {
        // 如果没有默认文件夹，创建一个
        if rootFolders.first(where: { $0.name == "笔记" && $0.isDefault }) == nil {
            let defaultFolder = Folder(name: "笔记", isDefault: true)
            modelContext.insert(defaultFolder)
            selectedFolder = defaultFolder
        }
    }
    
    private func createNewNote() {
        guard let folder = selectedFolder else { return }
        let newNote = Note(title: "新笔记")
        folder.notes.append(newNote)
        newNote.folder = folder
        selectedNote = newNote
    }
    
    private func createNewFolder() {
        let newFolder = Folder(name: newFolderName)
        modelContext.insert(newFolder)
        selectedFolder = newFolder
        selectedNote = nil
        showingNewFolderSheet = false
        newFolderName = ""
    }
    
    private func renameFolder() {
        guard let folder = folderToRename, !folder.isDefault else { return }
        folder.name = newFolderName
        folder.modifiedAt = Date()
        showingRenameSheet = false
        folderToRename = nil
        newFolderName = ""
    }
}

// 新建文件夹表单
struct NewFolderSheet: View {
    @Binding var isPresented: Bool
    @Binding var folderName: String
    let onSave: () -> Void
    
    var body: some View {
        NavigationStack {
            VStack {
                Form {
                    TextField("文件夹名称", text: $folderName)
                }
                .padding()
            }
            .frame(width: 300, height: 150)
            .navigationTitle("新建文件夹")
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        isPresented = false
                    }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("创建") {
                        onSave()
                    }
                    .disabled(folderName.isEmpty)
                }
            }
        }
    }
}

// 重命名文件夹表单
struct RenameFolderSheet: View {
    @Binding var isPresented: Bool
    @Binding var folderName: String
    let onSave: () -> Void
    
    var body: some View {
        NavigationStack {
            VStack {
                Form {
                    TextField("文件夹名称", text: $folderName)
                }
                .padding()
            }
            .frame(width: 300, height: 150)
            .navigationTitle("重命名文件夹")
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        isPresented = false
                    }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("重命名") {
                        onSave()
                    }
                    .disabled(folderName.isEmpty)
                }
            }
        }
    }
}

// 文件夹列表视图
struct FolderListView: View {
    let folders: [Folder]
    @Binding var selectedFolder: Folder?
    @Binding var selectedNote: Note?
    let onNewFolder: () -> Void
    let onRenameFolder: (Folder) -> Void
    @Environment(\.modelContext) private var modelContext
    @State private var showingNewSubfolderSheet = false
    @State private var parentFolder: Folder?
    @State private var newFolderName = ""
    
    var defaultFolder: Folder? {
        folders.first { $0.isDefault }
    }
    
    var customFolders: [Folder] {
        folders.filter { !$0.isDefault }
    }
    
    var body: some View {
        VStack {
            List {
                // 笔记区域
                if let notesFolder = defaultFolder {
                    Section {
                        FolderRowView(
                            folder: notesFolder,
                            selectedFolder: $selectedFolder,
                            selectedNote: $selectedNote,
                            onRename: { onRenameFolder(notesFolder) },
                            onNewSubfolder: {
                                parentFolder = notesFolder
                                newFolderName = ""
                                showingNewSubfolderSheet = true
                            }
                        )
                    }
                }
                
                // 自定义文件夹区域
                if !customFolders.isEmpty {
                    Section("文件夹") {
                        ForEach(customFolders) { folder in
                            FolderRowView(
                                folder: folder,
                                selectedFolder: $selectedFolder,
                                selectedNote: $selectedNote,
                                onRename: { onRenameFolder(folder) },
                                onNewSubfolder: {
                                    parentFolder = folder
                                    newFolderName = ""
                                    showingNewSubfolderSheet = true
                                }
                            )
                        }
                    }
                }
            }
            
            Button(action: onNewFolder) {
                HStack {
                    Image(systemName: "folder.badge.plus")
                    Text("新建文件夹")
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 8)
            }
            .buttonStyle(.borderless)
            .padding(.horizontal)
            .padding(.bottom, 8)
        }
        .sheet(isPresented: $showingNewSubfolderSheet) {
            NewFolderSheet(
                isPresented: $showingNewSubfolderSheet,
                folderName: $newFolderName,
                onSave: {
                    if !newFolderName.isEmpty {
                        createSubfolder(in: parentFolder!)
                    }
                }
            )
        }
    }
    
    private func deleteFolder(_ folder: Folder) {
        if folder.isDefault { return }  // 不允许删除默认文件夹
        if selectedFolder?.id == folder.id {
            selectedFolder = nil
            selectedNote = nil
        }
        modelContext.delete(folder)
    }
    
    private func createSubfolder(in parent: Folder) {
        let newFolder = Folder(name: newFolderName, parent: parent)
        parent.subfolders.append(newFolder)
        modelContext.insert(newFolder)
        selectedFolder = newFolder
        selectedNote = nil
        showingNewSubfolderSheet = false
        newFolderName = ""
    }
}

// 文件夹行视图
struct FolderRowView: View {
    let folder: Folder
    @Binding var selectedFolder: Folder?
    @Binding var selectedNote: Note?
    let onRename: () -> Void
    let onNewSubfolder: () -> Void
    @Environment(\.modelContext) private var modelContext
    @State private var isHovered = false
    
    var sortedNotes: [Note] {
        folder.notes.sorted { $0.modifiedAt > $1.modifiedAt }
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            HStack(spacing: 4) {
                if !folder.subfolders.isEmpty {
                    Button(action: {
                        folder.isExpanded?.toggle()
                    }) {
                        Image(systemName: (folder.isExpanded ?? true) ? "chevron.compact.down" : "chevron.compact.right")
                            .font(.system(size: 12))
                            .foregroundColor(.secondary)
                            .frame(width: 16, height: 16)
                    }
                    .buttonStyle(.plain)
                } else {
                    Image(systemName: "chevron.compact.right")
                        .font(.system(size: 12))
                        .foregroundColor(.clear)
                        .frame(width: 16, height: 16)
                }
                
                Image(systemName: "folder")
                    .font(.system(size: 14))
                Text(folder.name)
                
                Spacer(minLength: 0)
                
                if !folder.isDefault {  // 只有非默认文件夹显示菜单
                    Menu {
                        Button(action: onRename) {
                            Label("重命名", systemImage: "pencil")
                        }
                        
                        Button(action: onNewSubfolder) {
                            Label("新建子文件夹", systemImage: "folder.badge.plus")
                        }
                        
                        Button(role: .destructive, action: {
                            deleteFolder(folder)
                        }) {
                            Label("删除", systemImage: "trash")
                        }
                    } label: {
                        Image(systemName: "ellipsis.circle")
                            .font(.system(size: 14))
                            .foregroundColor(.secondary)
                    }
                    .buttonStyle(.plain)
                    .opacity(isHovered ? 1 : 0)
                    .animation(.easeInOut(duration: 0.2), value: isHovered)
                }
            }
            .padding(.vertical, 4)
            .padding(.horizontal, 8)
            .background(
                RoundedRectangle(cornerRadius: 6)
                    .fill(selectedFolder?.id == folder.id ? Color.accentColor.opacity(0.1) : Color.clear)
            )
            .contentShape(Rectangle())
            .onTapGesture {
                selectedFolder = folder
                selectedNote = sortedNotes.first
            }
            .onHover { hovering in
                isHovered = hovering
            }
            
            if (folder.isExpanded ?? true) && !folder.subfolders.isEmpty {
                ForEach(folder.subfolders) { subfolder in
                    FolderRowView(
                        folder: subfolder,
                        selectedFolder: $selectedFolder,
                        selectedNote: $selectedNote,
                        onRename: onRename,
                        onNewSubfolder: onNewSubfolder
                    )
                    .padding(.leading, 20)
                }
            }
        }
        .foregroundColor(selectedFolder?.id == folder.id ? .accentColor : .primary)
    }
    
    private func deleteFolder(_ folder: Folder) {
        if folder.isDefault { return }  // 不允许删除默认文件夹
        if selectedFolder?.id == folder.id {
            selectedFolder = nil
            selectedNote = nil
        }
        modelContext.delete(folder)
    }
}

// 笔记列表视图
struct NoteListView: View {
    let selectedFolder: Folder?
    @Binding var selectedNote: Note?
    
    var sortedNotes: [Note] {
        guard let folder = selectedFolder else { return [] }
        return folder.notes.sorted { $0.modifiedAt > $1.modifiedAt }
    }
    
    var body: some View {
        List {
            if let folder = selectedFolder {
                if sortedNotes.isEmpty {
                    Text("还没有笔记~")
                        .foregroundColor(.secondary)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .listRowBackground(Color.clear)
                } else {
                    ForEach(sortedNotes) { note in
                        NoteRow(note: note, isSelected: selectedNote?.id == note.id)
                            .onTapGesture {
                                selectedNote = note
                            }
                    }
                }
            } else {
                Text("选择一个文件夹")
                    .foregroundColor(.secondary)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .listRowBackground(Color.clear)
            }
        }
    }
}

// 笔记行视图
struct NoteRow: View {
    let note: Note
    let isSelected: Bool
    
    var body: some View {
        VStack(alignment: .leading) {
            Text(note.title)
                .font(.headline)
            Text(note.modifiedAt, style: .date)
                .font(.caption)
                .foregroundColor(.secondary)
        }
        .foregroundColor(isSelected ? .accentColor : .primary)
    }
}

// 笔记编辑视图
struct NoteEditorView: View {
    @Environment(\.modelContext) private var modelContext
    let note: Note
    @State private var title: String
    @State private var content: String
    @State private var isMarkdown: Bool
    
    init(note: Note) {
        self.note = note
        _title = State(initialValue: note.title)
        _content = State(initialValue: note.content)
        _isMarkdown = State(initialValue: note.isMarkdown)
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // 工具栏
            HStack {
                TextField("标题", text: $title)
                    .font(.title)
                    .textFieldStyle(.plain)
                    .onChange(of: title) { _, newValue in
                        note.title = newValue
                        note.modifiedAt = Date()
                    }
                
                Spacer()
                
                Toggle("Markdown", isOn: $isMarkdown)
                    .toggleStyle(.switch)
                    .onChange(of: isMarkdown) { _, newValue in
                        note.isMarkdown = newValue
                        note.modifiedAt = Date()
                    }
            }
            .padding()
            
            Divider()
            
            // 编辑区域
            if note.isMarkdown {
                TextEditor(text: $content)
                    .font(.system(.body, design: .monospaced))
                    .onChange(of: content) { _, newValue in
                        note.content = newValue
                        note.modifiedAt = Date()
                    }
            } else {
                TextEditor(text: $content)
                    .font(.body)
                    .onChange(of: content) { _, newValue in
                        note.content = newValue
                        note.modifiedAt = Date()
                    }
            }
        }
        .onChange(of: note) { _, newNote in
            // 当笔记改变时，更新所有状态
            title = newNote.title
            content = newNote.content
            isMarkdown = newNote.isMarkdown
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: [Folder.self, Note.self], inMemory: true)
}
